import Axios from 'axios'
import { ElMessage, ElLoading } from 'element-plus'
import { userModule } from '@/common/store/modules/user'

const BASE_URL = '/api'

const baseUrl: any = process.env.VUE_APP_BASE_API
// Axios.defaults.timeout = 5000
const service = Axios.create({
  baseURL: baseUrl,
  responseType: 'json',
  timeout: 30000
  // timeout: 5000
})
const ignoreName: any = [
  // 后端返回success: false的时候，如不想提示message,可把接口名加入到此数组中，切记要备注好每个接口名的意思
  // '/im-center/action/webchat/replyMsg', // 在线发送消息接口
  // '/call/action/biz/dialOut' // 外呼接口
]
// count不为0有遮照
let count = 0
let loadingInstance: any = null
service.interceptors.request.use(
  (res: any) => {
    const USERMODULE = userModule()
    if (res.hideLoading) {
      // 取消loading
      count = 0
      loadingInstance.close()
    } else {
      // 需要loading
      count++
      loadingInstance = ElLoading.service({ background: 'rgba(0,0,0,0)', spinner: 'a' })
    }
    const loginToken = USERMODULE.loginToken || ''
    const sessionId = USERMODULE.sessionId || ''
    const clientType = USERMODULE.clientType || 0
    let lang = window.localStorage.getItem('lang')
    if (!lang) {
      lang = 'zh_CN'
    }
    if (loginToken) {
      console.log('header token', loginToken)
      res.headers.loginToken = loginToken
      // res.headers.loginToken = '7moordev'
    }
    if (sessionId) {
      res.headers.sessionId = sessionId
    }
    res.headers.clientType = clientType
    res.headers.lang = lang // 当前选择的语言版本，用于后台国际化
    if (count > 0) {
      setTimeout(() => {
        loadingInstance.close() // 15S之后关闭遮罩
      }, 15000)
    }
    // if (process.env.VUE_APP_ENTRY !== 'main') {
    //   // res.headers['Access-Control-Allow-Origin'] = '*'
    // }
    return res
  },
  (error) => {
    count = 0
    loadingInstance.close()
    Promise.reject(error)
  }
)
service.interceptors.response.use(
  (response: any) => {
    count--
    if (count <= 0) {
      // 所有请求都返回了，关掉loading
      count = 0
      loadingInstance.close()
    }
    const res = response.data
    const config = response.config
    if (res.success) {
      return response
    } else {
      if (config.url && ignoreName.indexOf(config.url) > -1) {
        // 忽略后端的message提示
      } else {
        if (res.message) {
          ElMessage({
            message: res.message,
            type: 'error',
            duration: 5 * 1000
          })
        }
        if (res.code && res.code === '00000403') {
          const USERMODULE = userModule()
          USERMODULE.backLogin()
        }
      }
      return Promise.reject(response)
    }
  },
  (err) => {
    count = 0
    loadingInstance.close()
    ElMessage({
      message: err.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(err)
  }
)

export default (req: any) => {
  req.method === 'GET' ? delete req.data : delete req.params // get 参数用params， post 用data
  req.url = BASE_URL + req.url
  return service(req).then((res) => {
    return res.data
  })
}
